﻿package test;

import java.util.Arrays;
import java.util.Random;

/**
 * 自定义节点
 * */
public class Base5 {
	public static void main(String[] args) {
		int a[] = createArray(10);
		System.out.println(Arrays.toString(a));
		Node node = new Node();
		node.setValue(a[0]);
		for (int i = 1; i < a.length; i++) {
			node.addVaue(a[i]);
		}
		node.printNode();
		System.out.println("\n"+"contains 5 ? : "+node.containsValue(5));
	}

	private static int[] createArray(int length) {
		int[] a = new int[length];
		for (int i = 0; i < length - 1; i++) {
			a[i] = new Random().nextInt(10);
		}
		return a;
	}

}

class Node {
	private int value;
	private Node left;
	private Node right;

	// 设值
	public void setValue(int value) {
		this.value = value;
	}

	// 取值
	public int getValue() {
		return this.value;
	}

	// 查找
	public boolean containsValue(int value) {
		if (value == this.value) {
			return true;
		} else if (value < this.value) {
			if (this.left == null) {
				return false;
			}
			return this.left.containsValue(value);
		} else {
			if (this.right == null) {
				return false;
			}
			return this.right.containsValue(value);
		}
	}

	// 添加值
	public void addVaue(int value) {
		if (value < this.value) {
			if (this.left == null) {
				this.left = new Node();
				this.left.value = value;
			} else {
				this.left.addVaue(value);
			}
		} else {
			if (this.right == null) {
				this.right = new Node();
				this.right.value = value;
			} else {
				this.right.addVaue(value);
			}
		}
	}

	// 打印
	public void printNode() {
		System.out.print(this.value+",");
		if (this.left != null) {
			this.left.printNode();
		}
		if (this.right != null) {
			this.right.printNode();
		}
	}
}